import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import java.util.*;
import java.util.List;
import javax.swing.Timer; // 明确使用Swing Timer

// 数据库连接工具类
class DBUtil {
    // 数据库连接配置 - 请根据实际情况修改
    private static final String URL = "jdbc:mysql://localhost:3306/exam_system?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
    private static final String USER = "root";
    private static final String PASSWORD = "123456"; // 请确保与您的数据库密码一致

    public static Connection getConnection() {
        try {
            // 加载JDBC驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (ClassNotFoundException e) {
            JOptionPane.showMessageDialog(null, "未找到MySQL JDBC驱动，请添加mysql-connector-java依赖", "驱动错误", JOptionPane.ERROR_MESSAGE);
            throw new RuntimeException("JDBC驱动未找到", e);
        } catch (SQLException e) {
            String errorMsg = "数据库连接失败，请检查：\n" +
                    "1. MySQL服务是否启动\n" +
                    "2. 用户名和密码是否正确\n" +
                    "3. 数据库'exam_system'是否存在\n" +
                    "错误详情：" + e.getMessage();
            JOptionPane.showMessageDialog(null, errorMsg, "连接错误", JOptionPane.ERROR_MESSAGE);
            throw new RuntimeException("数据库连接异常", e);
        }
    }

    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if (rs != null) rs.close();
            if (stmt != null) stmt.close();
            if (conn != null) conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

// 用户实体类
class User {
    private int id;
    private String username;
    private String password;
    private int role; // 0: 学生, 1: 教师

    public User(int id, String username, String password, int role) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.role = role;
    }

    // Getters and setters
    public int getId() { return id; }
    public String getUsername() { return username; }
    public String getPassword() { return password; }
    public int getRole() { return role; }
}

// 题目实体类
class Question {
    private int id;
    private String content;
    private String optionA;
    private String optionB;
    private String optionC;
    private String optionD;
    private String answer;
    private int type; // 1: 单选题, 2: 多选题, 3: 判断题

    public Question(int id, String content, String optionA, String optionB, String optionC, String optionD, String answer, int type) {
        this.id = id;
        this.content = content;
        this.optionA = optionA;
        this.optionB = optionB;
        this.optionC = optionC;
        this.optionD = optionD;
        this.answer = answer;
        this.type = type;
    }

    // Getters and setters
    public int getId() { return id; }
    public String getContent() { return content; }
    public String getOptionA() { return optionA; }
    public String getOptionB() { return optionB; }
    public String getOptionC() { return optionC; }
    public String getOptionD() { return optionD; }
    public String getAnswer() { return answer; }
    public int getType() { return type; }
}

// 考试实体类
class Exam {
    private int id;
    private String title;
    private int duration; // 考试时长(分钟)
    private List<Question> questions;

    public Exam(int id, String title, int duration, List<Question> questions) {
        this.id = id;
        this.title = title;
        this.duration = duration;
        this.questions = questions;
    }

    // Getters and setters
    public int getId() { return id; }
    public String getTitle() { return title; }
    public int getDuration() { return duration; }
    public List<Question> getQuestions() { return questions; }
}

// 用户DAO类
class UserDAO {
    public User login(String username, String password) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        User user = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setString(1, username);
            stmt.setString(2, password);
            rs = stmt.executeQuery();

            if (rs.next()) {
                int id = rs.getInt("id");
                int role = rs.getInt("role");
                user = new User(id, username, password, role);
            } else {
                JOptionPane.showMessageDialog(null, "用户名或密码错误", "登录失败", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "登录查询失败：" + e.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stmt, rs);
        }

        return user;
    }
}

// 题目DAO类
class QuestionDAO {
    public List<Question> getQuestionsByExamId(int examId) {
        List<Question> questions = new ArrayList<>();
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT q.* FROM question q " +
                    "JOIN exam_question eq ON q.id = eq.question_id " +
                    "WHERE eq.exam_id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, examId);
            rs = stmt.executeQuery();

            while (rs.next()) {
                int id = rs.getInt("id");
                String content = rs.getString("content");
                String optionA = rs.getString("optionA");
                String optionB = rs.getString("optionB");
                String optionC = rs.getString("optionC");
                String optionD = rs.getString("optionD");
                String answer = rs.getString("answer");
                int type = rs.getInt("type");

                questions.add(new Question(id, content, optionA, optionB, optionC, optionD, answer, type));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "获取题目失败：" + e.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stmt, rs);
        }

        return questions;
    }
}

// 考试DAO类
class ExamDAO {
    public Exam getExamById(int examId) {
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        Exam exam = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "SELECT * FROM exam_paper WHERE id = ?";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, examId);
            rs = stmt.executeQuery();

            if (rs.next()) {
                String title = rs.getString("title");
                int duration = rs.getInt("duration");

                QuestionDAO questionDAO = new QuestionDAO();
                List<Question> questions = questionDAO.getQuestionsByExamId(examId);

                exam = new Exam(examId, title, duration, questions);
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "获取考试信息失败：" + e.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stmt, rs);
        }

        return exam;
    }

    public List<Exam> getAllExams() {
        List<Exam> exams = new ArrayList<>();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            conn = DBUtil.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery("SELECT * FROM exam_paper");

            while (rs.next()) {
                int id = rs.getInt("id");
                String title = rs.getString("title");
                int duration = rs.getInt("duration");

                QuestionDAO questionDAO = new QuestionDAO();
                List<Question> questions = questionDAO.getQuestionsByExamId(id);

                exams.add(new Exam(id, title, duration, questions));
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "获取考试列表失败：" + e.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stmt, rs);
        }

        return exams;
    }
}

// 主界面
class MainFrame extends JFrame {
    private User user;

    public MainFrame(User user) {
        this.user = user;
        initComponents();
    }

    private void initComponents() {
        setTitle("在线考试系统 - " + (user.getRole() == 1 ? "教师端" : "学生端"));
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        // 根据用户角色显示不同的界面
        if (user.getRole() == 1) {
            setupTeacherUI();
        } else {
            setupStudentUI();
        }
    }

    private void setupTeacherUI() {
        JPanel panel = new JPanel(new BorderLayout());

        // 顶部菜单
        JMenuBar menuBar = new JMenuBar();
        JMenu examMenu = new JMenu("考试管理");
        JMenuItem createExamItem = new JMenuItem("创建考试");
        JMenuItem manageExamItem = new JMenuItem("管理考试");
        examMenu.add(createExamItem);
        examMenu.add(manageExamItem);
        menuBar.add(examMenu);

        JMenu questionMenu = new JMenu("题库管理");
        JMenuItem addQuestionItem = new JMenuItem("添加题目");
        JMenuItem manageQuestionItem = new JMenuItem("管理题目");
        questionMenu.add(addQuestionItem);
        questionMenu.add(manageQuestionItem);
        menuBar.add(questionMenu);

        setJMenuBar(menuBar);

        // 主面板
        JLabel welcomeLabel = new JLabel("欢迎，教师 " + user.getUsername() + "！", JLabel.CENTER);
        welcomeLabel.setFont(new Font("宋体", Font.PLAIN, 24));
        panel.add(welcomeLabel, BorderLayout.CENTER);

        add(panel);
    }

    private void setupStudentUI() {
        JPanel panel = new JPanel(new BorderLayout());

        // 顶部菜单
        JMenuBar menuBar = new JMenuBar();
        JMenu examMenu = new JMenu("考试");
        JMenuItem availableExamsItem = new JMenuItem("可用考试");
        JMenuItem examHistoryItem = new JMenuItem("考试历史");
        examMenu.add(availableExamsItem);
        examMenu.add(examHistoryItem);
        menuBar.add(examMenu);

        setJMenuBar(menuBar);

        // 主面板
        JLabel welcomeLabel = new JLabel("欢迎，学生 " + user.getUsername() + "！", JLabel.CENTER);
        welcomeLabel.setFont(new Font("宋体", Font.PLAIN, 24));
        panel.add(welcomeLabel, BorderLayout.CENTER);

        // 可用考试列表
        ExamDAO examDAO = new ExamDAO();
        List<Exam> exams = examDAO.getAllExams();

        if (exams.size() > 0) {
            JPanel examPanel = new JPanel(new GridLayout(exams.size() + 1, 2));
            examPanel.setBorder(BorderFactory.createTitledBorder("可用考试"));

            examPanel.add(new JLabel("考试名称"));
            examPanel.add(new JLabel("操作"));

            for (Exam exam : exams) {
                examPanel.add(new JLabel(exam.getTitle()));

                JButton takeExamButton = new JButton("参加考试");
                takeExamButton.addActionListener(e -> {
                    dispose();
                    new ExamFrame(user, exam).setVisible(true);
                });
                examPanel.add(takeExamButton);
            }

            panel.add(examPanel, BorderLayout.SOUTH);
        }

        add(panel);
    }
}

// 考试界面
class ExamFrame extends JFrame {
    private User user;
    private Exam exam;
    private List<Question> questions;
    private Map<Integer, String> answers = new HashMap<>();
    private int currentQuestionIndex = 0;
    private Timer timer; // javax.swing.Timer
    private int remainingTime;
    private JLabel timerLabel;

    public ExamFrame(User user, Exam exam) {
        this.user = user;
        this.exam = exam;
        this.questions = exam.getQuestions();
        this.remainingTime = exam.getDuration() * 60; // 转换为秒

        initComponents();
        startTimer();
    }

    private void initComponents() {
        setTitle("考试：" + exam.getTitle());
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                if (JOptionPane.showConfirmDialog(
                        ExamFrame.this,
                        "确定要退出考试吗？未提交的答案将丢失。",
                        "确认退出",
                        JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                    if (timer != null) {
                        timer.stop();
                    }
                    dispose();
                }
            }
        });
        setLocationRelativeTo(null);

        displayCurrentQuestion();
    }

    private void displayCurrentQuestion() {
        getContentPane().removeAll();

        if (currentQuestionIndex >= questions.size()) {
            // 所有题目已完成，显示提交页面
            JPanel submitPanel = new JPanel(new BorderLayout());
            JLabel messageLabel = new JLabel("您已完成所有题目，确认提交？", JLabel.CENTER);
            messageLabel.setFont(new Font("宋体", Font.PLAIN, 20));

            JButton submitButton = new JButton("提交考试");
            submitButton.addActionListener(e -> submitExam());

            submitPanel.add(messageLabel, BorderLayout.CENTER);
            submitPanel.add(submitButton, BorderLayout.SOUTH);

            add(submitPanel);
        } else {
            // 显示当前题目
            Question question = questions.get(currentQuestionIndex);

            JPanel questionPanel = new JPanel(new BorderLayout());
            JPanel headerPanel = new JPanel(new BorderLayout());

            // 标题和计时器
            String typeLabel = "";
            switch (question.getType()) {
                case 1: typeLabel = "【单选题】"; break;
                case 2: typeLabel = "【多选题】"; break;
                case 3: typeLabel = "【判断题】"; break;
                default: typeLabel = "";
            }

            JLabel titleLabel = new JLabel("考试：" + exam.getTitle() + " - 题目 " + (currentQuestionIndex + 1) + "/" + questions.size() + " " + typeLabel + "每题5分");
            titleLabel.setFont(new Font("宋体", Font.BOLD, 16));

            timerLabel = new JLabel("剩余时间：" + formatTime(remainingTime));
            timerLabel.setFont(new Font("宋体", Font.BOLD, 16));
            timerLabel.setForeground(Color.RED);

            headerPanel.add(titleLabel, BorderLayout.WEST);
            headerPanel.add(timerLabel, BorderLayout.EAST);

            // 题目内容
            JPanel contentPanel = new JPanel(new BorderLayout());
            JLabel questionLabel = new JLabel("<html>" + question.getContent() + "</html>");
            questionLabel.setFont(new Font("宋体", Font.PLAIN, 16));
            contentPanel.add(questionLabel, BorderLayout.NORTH);

            // 选项面板
            JPanel optionsPanel = new JPanel();
            optionsPanel.setLayout(new BoxLayout(optionsPanel, BoxLayout.Y_AXIS));

            ButtonGroup buttonGroup = new ButtonGroup();

            JRadioButton optionARadio = new JRadioButton("A. " + question.getOptionA());
            JRadioButton optionBRadio = new JRadioButton("B. " + question.getOptionB());
            JRadioButton optionCRadio = new JRadioButton("C. " + question.getOptionC());
            JRadioButton optionDRadio = new JRadioButton("D. " + question.getOptionD());

            buttonGroup.add(optionARadio);
            buttonGroup.add(optionBRadio);
            buttonGroup.add(optionCRadio);
            buttonGroup.add(optionDRadio);

            // 如果已有答案，选中对应的选项
            String savedAnswer = answers.get(question.getId());
            if (savedAnswer != null) {
                switch (savedAnswer) {
                    case "A": optionARadio.setSelected(true); break;
                    case "B": optionBRadio.setSelected(true); break;
                    case "C": optionCRadio.setSelected(true); break;
                    case "D": optionDRadio.setSelected(true); break;
                }
            }

            optionsPanel.add(optionARadio);
            optionsPanel.add(optionBRadio);
            optionsPanel.add(optionCRadio);
            optionsPanel.add(optionDRadio);

            contentPanel.add(optionsPanel, BorderLayout.CENTER);

            // 按钮面板
            JPanel buttonPanel = new JPanel();

            JButton prevButton = new JButton("上一题");
            prevButton.addActionListener(e -> {
                saveCurrentAnswer(optionARadio, optionBRadio, optionCRadio, optionDRadio);
                currentQuestionIndex--;
                displayCurrentQuestion();
            });

            JButton nextButton = new JButton("下一题");
            nextButton.addActionListener(e -> {
                saveCurrentAnswer(optionARadio, optionBRadio, optionCRadio, optionDRadio);
                currentQuestionIndex++;
                displayCurrentQuestion();
            });

            if (currentQuestionIndex == 0) {
                prevButton.setEnabled(false);
            }

            if (currentQuestionIndex == questions.size() - 1) {
                nextButton.setText("完成");
            }

            buttonPanel.add(prevButton);
            buttonPanel.add(nextButton);

            questionPanel.add(headerPanel, BorderLayout.NORTH);
            questionPanel.add(contentPanel, BorderLayout.CENTER);
            questionPanel.add(buttonPanel, BorderLayout.SOUTH);

            add(questionPanel);
        }

        revalidate();
        repaint();
    }

    private void saveCurrentAnswer(JRadioButton optionARadio, JRadioButton optionBRadio,
                                   JRadioButton optionCRadio, JRadioButton optionDRadio) {
        Question question = questions.get(currentQuestionIndex);

        if (optionARadio.isSelected()) {
            answers.put(question.getId(), "A");
        } else if (optionBRadio.isSelected()) {
            answers.put(question.getId(), "B");
        } else if (optionCRadio.isSelected()) {
            answers.put(question.getId(), "C");
        } else if (optionDRadio.isSelected()) {
            answers.put(question.getId(), "D");
        } else {
            answers.put(question.getId(), "");
        }
    }

    private void startTimer() {
        timer = new Timer(1000, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                remainingTime--;
                if (timerLabel != null) {
                    timerLabel.setText("剩余时间：" + formatTime(remainingTime));
                }

                // 时间到，自动提交
                if (remainingTime <= 0) {
                    timer.stop();
                    submitExam();
                }
            }
        });
        timer.start();
    }

    private String formatTime(int seconds) {
        int minutes = seconds / 60;
        seconds = seconds % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    private void submitExam() {
        // 计算得分
        int score = 0;
        for (Question question : questions) {
            String userAnswer = answers.getOrDefault(question.getId(), "");
            if (userAnswer.equals(question.getAnswer())) {
                score += 5; // 每题5分
            }
        }

        // 保存考试结果到数据库
        saveExamResult(score);

        // 显示结果
        timer.stop();
        JOptionPane.showMessageDialog(
                this,
                "考试已提交！您的得分是：" + score,
                "考试完成",
                JOptionPane.INFORMATION_MESSAGE);

        dispose();
        new MainFrame(user).setVisible(true);
    }

    private void saveExamResult(int score) {
        Connection conn = null;
        PreparedStatement stmt = null;

        try {
            conn = DBUtil.getConnection();
            String sql = "INSERT INTO exam_record (user_id, exam_id, score, exam_date) VALUES (?, ?, ?, NOW())";
            stmt = conn.prepareStatement(sql);
            stmt.setInt(1, user.getId());
            stmt.setInt(2, exam.getId());
            stmt.setInt(3, score);
            stmt.executeUpdate();
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "保存考试结果失败：" + e.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stmt, null);
        }
    }
}

// 登录界面
class LoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;

    public LoginFrame() {
        initComponents();
    }

    private void initComponents() {
        setTitle("在线考试系统 - 登录");
        setSize(400, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JLabel titleLabel = new JLabel("在线考试系统");
        titleLabel.setFont(new Font("宋体", Font.BOLD, 24));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(titleLabel, gbc);

        JLabel usernameLabel = new JLabel("用户名：");
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 1;
        gbc.anchor = GridBagConstraints.LINE_END;
        panel.add(usernameLabel, gbc);

        usernameField = new JTextField(20);
        gbc.gridx = 1;
        gbc.gridy = 1;
        gbc.anchor = GridBagConstraints.LINE_START;
        panel.add(usernameField, gbc);

        JLabel passwordLabel = new JLabel("密码：");
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.anchor = GridBagConstraints.LINE_END;
        panel.add(passwordLabel, gbc);

        passwordField = new JPasswordField(20);
        gbc.gridx = 1;
        gbc.gridy = 2;
        gbc.anchor = GridBagConstraints.LINE_START;
        panel.add(passwordField, gbc);

        JButton loginButton = new JButton("登录");
        loginButton.addActionListener(e -> login());
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        gbc.anchor = GridBagConstraints.CENTER;
        panel.add(loginButton, gbc);

        add(panel);
    }

    private void login() {
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword());

        if (username.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名和密码不能为空！", "登录失败", JOptionPane.ERROR_MESSAGE);
            return;
        }

        UserDAO userDAO = new UserDAO();
        User user = userDAO.login(username, password);

        if (user != null) {
            dispose();
            new MainFrame(user).setVisible(true);
        }
    }
}

// 主程序入口
public class OnlineExamSystem {
    public static void main(String[] args) {
        // 初始化数据库
        initDatabase();

        // 显示登录界面
        SwingUtilities.invokeLater(() -> {
            new LoginFrame().setVisible(true);
        });
    }

    private static void initDatabase() {
        Connection conn = null;
        Statement stmt = null;

        try {
            conn = DBUtil.getConnection();
            stmt = conn.createStatement();

            // 创建用户表
            String createUserTable = "CREATE TABLE IF NOT EXISTS user (" +
                    "id INT PRIMARY KEY AUTO_INCREMENT," +
                    "username VARCHAR(50) NOT NULL UNIQUE," +
                    "password VARCHAR(50) NOT NULL," +
                    "role INT NOT NULL DEFAULT 0" + // 0: 学生, 1: 教师
                    ")";
            stmt.executeUpdate(createUserTable);

            // 创建题库表
            String createQuestionTable = "CREATE TABLE IF NOT EXISTS question (" +
                    "id INT PRIMARY KEY AUTO_INCREMENT," +
                    "content TEXT NOT NULL," +
                    "optionA VARCHAR(255) NOT NULL," +
                    "optionB VARCHAR(255) NOT NULL," +
                    "optionC VARCHAR(255) NOT NULL," +
                    "optionD VARCHAR(255) NOT NULL," +
                    "answer VARCHAR(10) NOT NULL," +
                    "type INT NOT NULL" + // 1: 单选题, 2: 多选题, 3: 判断题
                    ")";
            stmt.executeUpdate(createQuestionTable);

            // 创建试卷表
            String createExamTable = "CREATE TABLE IF NOT EXISTS exam_paper (" +
                    "id INT PRIMARY KEY AUTO_INCREMENT," +
                    "title VARCHAR(100) NOT NULL," +
                    "duration INT NOT NULL" + // 考试时长(分钟)
                    ")";
            stmt.executeUpdate(createExamTable);

            // 创建试卷-题目关联表
            String createExamQuestionTable = "CREATE TABLE IF NOT EXISTS exam_question (" +
                    "exam_id INT NOT NULL," +
                    "question_id INT NOT NULL," +
                    "PRIMARY KEY (exam_id, question_id)," +
                    "FOREIGN KEY (exam_id) REFERENCES exam_paper(id)," +
                    "FOREIGN KEY (question_id) REFERENCES question(id)" +
                    ")";
            stmt.executeUpdate(createExamQuestionTable);

            // 创建考试记录表
            String createExamRecordTable = "CREATE TABLE IF NOT EXISTS exam_record (" +
                    "id INT PRIMARY KEY AUTO_INCREMENT," +
                    "user_id INT NOT NULL," +
                    "exam_id INT NOT NULL," +
                    "score INT NOT NULL," +
                    "exam_date DATETIME NOT NULL," +
                    "FOREIGN KEY (user_id) REFERENCES user(id)," +
                    "FOREIGN KEY (exam_id) REFERENCES exam_paper(id)" +
                    ")";
            stmt.executeUpdate(createExamRecordTable);

            // 添加测试数据
            addTestData(conn);
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "初始化数据库失败：" + e.getMessage(), "数据库错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, stmt, null);
        }
    }

    private static void addTestData(Connection conn) throws SQLException {
        // 检查是否已有测试数据
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM user");
        rs.next();
        int userCount = rs.getInt(1);

        if (userCount > 0) {
            return; // 已有数据，不添加测试数据
        }

        // 添加测试用户
        String insertUserSql = "INSERT INTO user (username, password, role) VALUES (?, ?, ?)";
        PreparedStatement pstmt = conn.prepareStatement(insertUserSql);

        // 教师用户
        pstmt.setString(1, "teacher");
        pstmt.setString(2, "123456");
        pstmt.setInt(3, 1);
        pstmt.executeUpdate();

        // 学生用户
        pstmt.setString(1, "student1");
        pstmt.setString(2, "123456");
        pstmt.setInt(3, 0);
        pstmt.executeUpdate();

        // 添加测试题目
        String insertQuestionSql = "INSERT INTO question (content, optionA, optionB, optionC, optionD, answer, type) VALUES (?, ?, ?, ?, ?, ?, ?)";
        pstmt = conn.prepareStatement(insertQuestionSql, Statement.RETURN_GENERATED_KEYS);

        // 题目1: 单选题
        pstmt.setString(1, "Java是由哪家公司开发的？");
        pstmt.setString(2, "Microsoft");
        pstmt.setString(3, "Sun Microsystems");
        pstmt.setString(4, "Oracle");
        pstmt.setString(5, "IBM");
        pstmt.setString(6, "B");
        pstmt.setInt(7, 1); // 单选题
        pstmt.executeUpdate();

        // 题目2
        pstmt.setString(1, "以下哪个是Java的基本数据类型？");
        pstmt.setString(2, "String");
        pstmt.setString(3, "Integer");
        pstmt.setString(4, "boolean");
        pstmt.setString(5, "ArrayList");
        pstmt.setString(6, "C");
        pstmt.setInt(7, 1);
        pstmt.executeUpdate();

        // 题目3
        pstmt.setString(1, "在Java中，哪个关键字用于继承类？");
        pstmt.setString(2, "extends");
        pstmt.setString(3, "implements");
        pstmt.setString(4, "inherits");
        pstmt.setString(5, "extend");
        pstmt.setString(6, "A");
        pstmt.setInt(7, 1);
        pstmt.executeUpdate();

        // 题目4
        pstmt.setString(1, "Java中的哪个关键字用于异常处理？");
        pstmt.setString(2, "try");
        pstmt.setString(3, "catch");
        pstmt.setString(4, "finally");
        pstmt.setString(5, "以上都是");
        pstmt.setString(6, "D");
        pstmt.setInt(7, 1);
        pstmt.executeUpdate();

        // 题目5
        pstmt.setString(1, "以下哪个是Java集合框架中的接口？");
        pstmt.setString(2, "List");
        pstmt.setString(3, "Set");
        pstmt.setString(4, "Map");
        pstmt.setString(5, "以上都是");
        pstmt.setString(6, "D");
        pstmt.setInt(7, 1);
        pstmt.executeUpdate();

        // 题目6
        pstmt.setString(1, "Java中，哪个类用于文件操作？");
        pstmt.setString(2, "File");
        pstmt.setString(3, "FileInputStream");
        pstmt.setString(4, "FileOutputStream");
        pstmt.setString(5, "以上都是");
        pstmt.setString(6, "D");
        pstmt.setInt(7, 1);
        pstmt.executeUpdate();

        // 题目7
        pstmt.setString(1, "Java中的多态性是通过什么实现的？");
        pstmt.setString(2, "继承");
        pstmt.setString(3, "接口");
        pstmt.setString(4, "方法重写");
        pstmt.setString(5, "以上都是");
        pstmt.setString(6, "D");
        pstmt.setInt(7, 1);
        pstmt.executeUpdate();

        // 题目8
        pstmt.setString(1, "Java中的线程是通过哪个类实现的？");
        pstmt.setString(2, "Thread");
        pstmt.setString(3, "Runnable");
        pstmt.setString(4, "Callable");
        pstmt.setString(5, "以上都是");
        pstmt.setString(6, "D");
        pstmt.setInt(7, 1);
        pstmt.executeUpdate();

        // 题目9
        pstmt.setString(1, "以下哪个是Java的访问修饰符？");
        pstmt.setString(2, "public");
        pstmt.setString(3, "private");
        pstmt.setString(4, "protected");
        pstmt.setString(5, "以上都是");
        pstmt.setString(6, "D");
        pstmt.setInt(7, 1);
        pstmt.executeUpdate();

        // 题目10: 多选题
        pstmt.setString(1, "以下哪些是面向对象编程的主要特性？");
        pstmt.setString(2, "封装");
        pstmt.setString(3, "继承");
        pstmt.setString(4, "多态");
        pstmt.setString(5, "抽象");
        pstmt.setString(6, "ABCD"); // 多选题答案
        pstmt.setInt(7, 2); // 多选题
        pstmt.executeUpdate();

        // 创建测试试卷
        String insertExamSql = "INSERT INTO exam_paper (title, duration) VALUES (?, ?)";
        pstmt = conn.prepareStatement(insertExamSql, Statement.RETURN_GENERATED_KEYS);
        pstmt.setString(1, "Java基础知识测试");
        pstmt.setInt(2, 50); // 50分钟
        pstmt.executeUpdate();

        // 获取试卷ID
        rs = pstmt.getGeneratedKeys();
        int examId = 0;
        if (rs.next()) {
            examId = rs.getInt(1);
        }

        // 添加试卷-题目关联
        String insertExamQuestionSql = "INSERT INTO exam_question (exam_id, question_id) VALUES (?, ?)";
        pstmt = conn.prepareStatement(insertExamQuestionSql);

        // 获取所有题目ID
        stmt = conn.createStatement();
        rs = stmt.executeQuery("SELECT id FROM question");
        while (rs.next()) {
            int questionId = rs.getInt("id");
            pstmt.setInt(1, examId);
            pstmt.setInt(2, questionId);
            pstmt.executeUpdate();
        }

        pstmt.close();
        stmt.close();
        rs.close();
    }
}